<template>
    <div class="cart">
        <!-- 顶部数据，展示所有数据 -->
        <div class="header" style="display: flex; padding: 5px;">
            <div style="text-align: left; color: #ec0909; width: 50%; font-weight: bolder; font-family: cursive; font-size: 14px;">
                <span>全部商品 </span> <span>{{ total }}</span></div>
            
            <div style="text-align: right; width: 50%; font-size: small;"><span>配送至：</span> <span>陕西省西安市雁塔区曹家堡6号楼</span>
            </div>
        </div>
        
        <!-- 购物车数据 -->
        <div class="cart-list" ref="list" @scroll="handleScroll">
            <!-- 列表查询 -->
            <el-table :data="cartList" border stripe :header-cell-class-name="headerBg" v-loading="loading"
                      ref="carTable" @selection-change="handleSelectionChange">
                <el-table-column type="selection" label="全选" width="40" fixed="left"></el-table-column>
                <el-table-column prop="bookName" label="图书" width="500" align="center" style="padding: 0;">
                    <template slot-scope="scope">
                        <div class="book">
                            <div class="book-content" style="width: 100%; display: flex; flex-wrap: wrap;">
                                <div style="margin: 2px 0 2px 0; display: flex; border: 10px solid rgb(245 245 245);">
                                    <div class="img-box">
                                        <img :src="require('@/' + scope.row.bookImage)" class="imgbackground">
                                    </div>
                                    <div class="book-msg">
                                        <div style="height: 93%;">
                                            <h5>书名：{{ scope.row.bookName }}</h5>
                                            <p class="sales" title="书籍简介">书籍简介：{{
                                                    bookDes
                                                }}</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="bookPrice" label="单价" width="100" align="center">
                    <template slot-scope="scope">
                        ￥ {{ scope.row.bookPrice }}
                    </template>
                </el-table-column>
                <el-table-column prop="count" label="数量" width="160" align="center">
                    <template slot-scope="scope">
                        <el-button type="button" class="btn btn-light btn-sm shop-car-btn" @click="shopAdd(scope.row)">+</el-button>
                        <span style="margin: 0 20px;">
                        {{ scope.row.count }}
                    </span>
                        <el-button type="button" class="btn btn-light btn-sm shop-car-btn" @click="shopReduce(scope.row)">-</el-button>
                    </template>
                </el-table-column>
                <el-table-column prop="totalPrice" label="小计" width="100" align="center">
                    <template slot-scope="scope">
                        ￥ {{ scope.row.totalPrice }}
                    </template>
                </el-table-column>
                <el-table-column prop="updateTime" label="添加时间" width="200" align="center"></el-table-column>
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <el-button type="danger" size="mini" @click="shopRemove(scope.row)">移除 <i class="el-icon-remove-outline"></i></el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div v-if="loading">Loading...</div>
        </div>
        
        <!-- 底部结算  -->
        <div style="display: flex; font-size: 14px; background-color: rgb(255 223 132);">
            <div style="text-align: left; display: flex; width: 73%; padding: 5px 0;">
                <div style="text-align: left; display: flex;">
                    <el-checkbox style="margin: 2px 0 0 13px;" @change="changeAll(cartList)">全选</el-checkbox>
                </div>
                <div style="margin: 0 2%;">删除选中的数据</div>
                <div style="margin: 0 2%;">清理购物车</div>
            </div>
            <div style="text-align: right; display: flex; width: 20.4%;padding: 5px 0;">
                <div style="display: flex; margin: 0 2%;">已选择
                    <div style="color: red; width: 30px; padding: 2px; text-align: center;">{{ selectCount }}</div>
                    件商品
                </div>
                <div style="margin: 0 2%;">总价 <span style="color: red">￥{{ selectTotalPrice }}</span></div>
            </div>
            <div>
                <el-button style="background: #e64347; color: white; font-weight: bold; border-radius: 0;"
                           @click="shopSettle">去结算
                </el-button>
            </div>
        </div>
        
        <!-- 订单确认弹窗 -->
        <el-dialog
             title="订单信息确认"
             :visible.sync="orderVisible"
             width="50%"
             :before-close="orderClose">
            <el-form :modal="orderForm" ref="form" label-width="90px" style="display: flex;" :role="orderRoles">
                <div class="updateinfo">
                    <!-- 顶部信息 -->
                    <div class="header" style="display: flex; padding: 5px;">
                        <div style="text-align: left; color: #ec0909; width: 50%; font-weight: bolder; font-family: cursive; font-size: 14px;">
                            <span>共计商品 </span> <span>{{ selectCount }} 件</span>
                            <span>, 总价 ￥</span><span>{{ selectTotalPrice }} ，商品清单如下:</span>
                        </div>
                    </div>
                    
                    <div style="display: flex;">
                        <!-- 订单数据 -->
                        <el-table class="order-table" :data="orderList" border stripe
                                  :header-cell-class-name="headerBg">
                            <el-table-column prop="bookName" label="图书信息" width="400" align="center"
                                             style="padding: 0;">
                                <template slot-scope="scope">
                                    <div class="book">
                                        <div class="book-content" style="width: 100%; display: flex; flex-wrap: wrap;">
                                            <div style="margin: 2px 0 2px 0; display: flex; border: 10px solid rgb(245 245 245);">
                                                <div class="img-box-order">
                                                    <img :src="require('@/' + scope.row.bookImage)"
                                                         class="imgbackground">
                                                </div>
                                                <div class="book-msg-order">
                                                    <div style="height: 93%;">
                                                        <p class="sales" title="书籍简介">时光永远不会逆行，把握好每一个属于自己的清晨。早安。</p>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column prop="bookName" label="图书名称" width="100" align="center"></el-table-column>
                            <el-table-column prop="total" label="数量" width="100" align="center"></el-table-column>
                        </el-table>
                        
                        <!-- 订单右侧数据 -->
                        <div class="right">
                            <el-form-item label="收件人" prop="consignee">
                                <el-input v-model="orderForm.consignee"></el-input>
                            </el-form-item>
                            <el-form-item label="联系方式" prop="telephone">
                                <el-input v-model="orderForm.telephone"></el-input>
                            </el-form-item>
                            <el-form-item label="收件地址" prop="address">
                                <el-input v-model="orderForm.address"></el-input>
                            </el-form-item>
                            <div class="order-code-img">
                                <div class="pay-way">
                                    <ol>
                                        <li>
                                            <el-button type="success" size="mini"><span
                                                 style="margin-right: 12px;">微信</span> <i class="el-icon-edit"></i>
                                            </el-button>
                                        </li>
                                        <li>
                                            <el-button type="danger" size="mini">支付宝 <i
                                                 class="el-icon-remove-outline"></i></el-button>
                                        </li>
                                    </ol>
                                </div>
                                <el-image :src="orderQrcode" style="border: 1px #d5d5d5 solid;"/>
                            </div>
                        </div>
                    </div>
                </div>
            </el-form>
            
            <div class="footer-btn">
                  <span class="dialog-footer align-footer">
                        <el-button @click="orderClose">取 消</el-button>
                        <el-button type="primary" @click="orderSubmit">提 交</el-button>
                  </span>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {page, carShopAddOne, carShopReduceOne, carRemove} from "@/api/book/shopCar";
import {qrcode, removeQrcode, addOrder} from "@/api/book/order";

export default {
    name: "",
    data() {
        return {
            cartList: [],
            params: {},
            page: 1,
            pageSize: 5,
            loading: false,
            headerBg: 'headerBg',
            bookDes: '这个世界,不会偏爱任何一个不劳而获的人,当然也不会,辜负任何一个默默努力的人。 ' +
                 '爬在楼梯口，走廊上的藤蔓，映着明亮的月光，显得更加的翠绿。微风拂过，闪烁着银子一般的光。',
            total: 0, // 总数
            allSelect: false, // 全选
            
            selectedList: [], // 已选中数据
            selectCount: 0, // 已选中商品数量
            selectTotalPrice: 0, // 已选中商品总价
            
            orderVisible: false, // 订单展示弹窗
            orderList: [], // 订单数据集合
            
            orderForm: {
                address: '陕西省西安市雁塔区曹家堡6号楼', // 收货地址
                consignee: 'Enjoy', // 收货人
                telephone: '17809160681', // 联系方式
            }, // 订单表单
            
            orderRoles: {
                address: [
                    {required: true, message: '请输入收货地址', trigger: 'blur'},
                ],
                consignee: [
                    {required: true, message: '请输入收件人名称', trigger: 'blur'},
                ],
                telephone: [
                    {required: true, message: '请确认联系方式', trigger: 'blur'},
                ],
            }, // 订单表单规则
            
            orderQrcode: '', // 订单二维码地址
        };
    },
    methods: {
        loadMore() {
            this.loading = true;
            page(this.page, this.pageSize, this.params).then(res => {
                this.cartList.push(...res.data.records)
                this.total = res.data.total
                this.loading = false
            }).catch(() => this.loading = false)
        },
        handleScroll() {
            const list = this.$refs.list;
            if (!list) return; // 容错处理，如果 ref="list" 的元素不存在则直接返回
            if (list.scrollTop + list.clientHeight >= list.scrollHeight) { // 增加一个偏差值，避免误差
                if (!this.loading && this.total > this.cartList.length) {
                    this.page++;
                    this.loadMore();
                }
            }
        },
        
        // 全选
        changeAll(rows) {
            this.$refs.carTable.clearSelection();
            if (rows && !this.allSelect) {
                rows.forEach(row => {
                    this.$refs.carTable.toggleRowSelection(row);
                });
            }
            this.allSelect = !this.allSelect
            console.log("权限  ==============  行数据为：", this.selectedList)
            this.handleShopTotalPrice()
        },
        
        // 处理选中数据
        handleSelectionChange(rows) {
            this.selectedList = rows
            this.handleShopTotalPrice()
        },
        
        // 处理已选中商品总价
        handleShopTotalPrice() {
            this.selectCount = this.selectedList.length // 设置已选中数据数量
            let price = 0
            this.selectedList.forEach(shop => {
                price += shop.totalPrice * 1  // 数字字符串 * 1，可以让数字字符串转换为 数字
            })
            this.selectTotalPrice = price
        },
        
        // 商品结算
        shopSettle() {
            if (this.selectCount === 0) {
                this.$message.warning("暂无购买商品")
                return
            }
            
            this.orderList = []
            this.selectedList.forEach(book => {
                const order = {
                    bookId: book.id,
                    bookName: book.bookName,
                    bookImage: book.bookImage,
                    total: book.count,
                    price: book.bookPrice,
                    countPrice: book.bookPrice * 1 * book.count,
                }
                this.orderList.push(order)
            })
            
            let user = sessionStorage.getItem("admin-user") ? JSON.parse(sessionStorage.getItem("admin-user")) : {};
            qrcode(user.id, this.selectTotalPrice).then(res => {
                console.log(res)
                this.orderQrcode = res.msg
                this.orderVisible = true
            })
            
        },
    
        // 订单关闭事件
        orderClose() {
            // 订单关闭时，直接删除后端生成二维码，二维码过期
            removeQrcode(this.orderQrcode.substring(this.orderQrcode.lastIndexOf("/") + 1)).then(res => console.log(res))
            this.orderVisible = false
        },
        
        // 订单提交
        orderSubmit() {
            let user = sessionStorage.getItem("admin-user") ? JSON.parse(sessionStorage.getItem("admin-user")) : {};
            const order = {
                id: '',
                orderNumber: this.orderQrcode.substring(this.orderQrcode.lastIndexOf("/") + 1, this.orderQrcode.lastIndexOf(".png")),
                userId: user.id,
                consignee: this.orderForm.consignee, // 收件人
                telephone: this.orderForm.telephone, // 联系电话
                address: this.orderForm.address, // 收货地址
                totalPrice: this.selectTotalPrice, // 总价
                payWay: '微信',
                payStatus: '待支付',
                items: this.orderList,
            }
            addOrder(order)
                 .then(res => {
                     this.$message.success("订单已提交，请在订单列表查看")
                     this.orderVisible = false
                 }).catch(err => err)
        },
        
        // 商品 + 1
        shopAdd(shop) {
            carShopAddOne(shop).then(() => {
                this.cartList = []
                this.page = 1
                this.loadMore()
            })
        },
        
        // 商品 - 1
        shopReduce(shop) {
            if (shop.count === 0 || shop.count === '0') {
                return
            }
            carShopReduceOne(shop).then(() => {
                this.cartList = []
                this.page = 1
                this.loadMore()
            })
        },
        
        // 移除商品
        shopRemove(shop) {
            carRemove(shop).then(() => {
                this.cartList = []
                this.page = 1
                this.loadMore()
            })
        }
    },
    async mounted() {
        this.loadMore()
    },
};
</script>

<style scoped>
.cart-list {
    height: 600px;
    overflow-y: scroll;
}

.order-table {
    height: 300px;
    overflow-y: scroll;
}

.align-footer {
    text-align: center;
}

.avatar-uploader {
    width: 80px;
    height: 80px;
    border: 1px #b6b9c1 solid;
}

.img-box {
    /*width: 200px;*/
    height: 80px;
    background-size: cover;
    background-position: center;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
}

.img-box .imgbackground {
    width: 80px;
    height: 80px;
}

.book {
    display: flex;
    margin: 0 -10px 0 -10px
    /*margin: 0 17.8% 0 17.8%;*/
    /*width: 33%;*/
}

.book-msg {
    width: 380px;
    text-align: left;
    margin: 0 9px 0 9px;
}

.book-msg p {
    margin-top: 5px;
    line-height: 1.5;
    font-size: smaller;
}

.book-msg h5 {
    font-size: smaller;
    margin-bottom: 5px;
}

.shop-car-btn {
    padding: 4px 14px;
}

.cart {
    margin: 0 17.8%;
}


/* 滚动条 */
/* 隐藏滚动条 */
::-webkit-scrollbar {
    width: 1px !important;
}

/* 滚动条背景颜色 */
::-webkit-scrollbar {
    background-color: #999292 !important;
}


/* 订单 */
.img-box-order .imgbackground {
    width: 80px;
    height: 40px;
    margin-bottom: -6px;
}

.book-msg-order {
    width: 280px;
    text-align: left;
    margin: 0 9px 0 9px;
}

.book-msg-order p {
    margin-top: 3px;
    line-height: 1.5;
    font-size: smaller;
}

/* 订单界面右侧数据 */
.right {
    width: 32.7%;
}

.right >>> input {
    height: 33px;
}

.right .el-form-item {
    margin-bottom: 20px;
}

/* 支付二维码 */
.order-code-img {
    display: flex;
}

.pay-way {
    width: 40%;
    padding-left: 20px;
    text-align: left;
}

.pay-way li {
    margin-bottom: 15px;
}

.footer-btn {
    margin: 10px 0 -20px 0;
}
</style>
